package com.virtualCat.controller.portal;

import com.google.common.collect.Maps;
import com.virtualCat.common.Msg;
import com.virtualCat.service.WeChatPayService;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/wxPay")
@Api(value = "微信支付",description="支付")
public class WeChatOrderController {
    @Autowired
    WeChatPayService weChatPayService;

    private static Log log = LogFactory.getLog(WeChatOrderController.class);

    /**
     * 统一下单
     * @return
     */
    @RequestMapping(value = "/unifiedOrder",method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value="12.统一下单",httpMethod="POST",notes="统一下单")
    @ResponseBody
    public Msg unifiedOrder(@RequestParam("openid") String openid,
                            @RequestParam("cat_id") String cat_id){
        log.info("========微信统一下单=========");
        if (StringUtils.isNotBlank(openid)&&StringUtils.isNotBlank(cat_id)){
            Map<String,Object> map = Maps.newHashMap();
            map.put("openid", openid);
            map.put("cat_id",cat_id);
            return weChatPayService.unifiedOrder(map);
        }
        return Msg.fail().add("参数错误","11201");
    }

    /**
     * 微信异步回调，不会跳转页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/notifyUrl.do",method = RequestMethod.POST)
    public Msg weixinReceive(HttpServletRequest request,HttpServletResponse response){
        return weChatPayService.weiXinReceive(request,response);
    }

    /**
     * 查询微信后台是否支付成功，然后跳转结果页面
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/success",method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value="13.支付成功查询",httpMethod="POST",notes="支付成功查询")
    @ResponseBody
    public Msg toWXPaySuccess(@RequestParam("pay_id") String pay_id){
        if (StringUtils.isNotBlank(pay_id)){
            return weChatPayService.toWXPaySuccess(pay_id);
        }
       return Msg.fail().add("参数为空","101201");
    }

}
